<template>
  <el-container class="layout-container">
    <!-- 顶部黑条导航 -->
    <div class="top-bar">
      <div class="top-bar-content">
        <div class="top-bar-left">
          <el-input
            v-model="searchKeyword"
            placeholder="What are you looking for?"
            class="top-search-input"
            @keyup.enter="handleSearch"
            size="small"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div class="top-bar-center">
          <h1 class="brand-name" @click="$router.push('/')">在线商城</h1>
        </div>
        <div class="top-bar-right">
          <el-button v-if="!currentUser" @click="$router.push('/login')" text class="top-link">Login</el-button>
          <el-dropdown v-else>
            <span class="top-link">
                {{ currentUser.username }}
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
        </div>
      </div>
          </div>
          
    <!-- 主导航栏 -->
    <el-header class="header" height="60px">
      <div class="header-content">
        <div class="logo-area">
          <h2 class="logo" @click="$router.push('/')">在线商城</h2>
          </div>
        
        <el-menu
          mode="horizontal"
          :default-active="activeMenu"
          @select="handleMenuSelect"
          class="main-menu"
        >
          <el-menu-item index="home">首页</el-menu-item>
          <el-sub-menu v-for="category in categories" :key="category.key" :index="category.key">
            <template #title>{{ category.name }}</template>
            <el-menu-item :index="`${category.key}-all`" @click="router.push(`/category/${category.key}`)">所有产品</el-menu-item>
            <el-menu-item v-for="sub in getSubCategories(category.key)" :key="sub.key" :index="`${category.key}-${sub.key}`" @click="router.push(`/category/${category.key}`)">
              {{ sub.name }}
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
        
        <div class="header-right">
          <el-button @click="$router.push('/cart')" text class="cart-button">
            <el-icon><ShoppingCart /></el-icon>
            <el-badge :value="cartCount" :hidden="cartCount === 0" class="cart-badge" />
          </el-button>
        </div>
      </div>
    </el-header>

    <!-- 主内容区（全宽布局，已移除侧边栏） -->
      <el-main class="main-content">
        <slot />
      </el-main>

    <!-- 页脚 -->
    <el-footer class="footer" height="auto">
      <div class="footer-content">
        <div class="footer-section">
          <h3 class="footer-title">关于我们</h3>
          <ul class="footer-links">
            <li><a href="#" @click.prevent>品牌故事</a></li>
            <li><a href="#" @click.prevent>联系我们</a></li>
            <li><a href="#" @click.prevent>加入我们</a></li>
          </ul>
        </div>
        <div class="footer-section">
          <h3 class="footer-title">客户服务</h3>
          <ul class="footer-links">
            <li><a href="#" @click.prevent>帮助中心</a></li>
            <li><a href="#" @click.prevent>配送说明</a></li>
            <li><a href="#" @click.prevent>退换货政策</a></li>
          </ul>
        </div>
        <div class="footer-section">
          <h3 class="footer-title">关注我们</h3>
          <ul class="footer-links">
            <li><a href="#" @click.prevent>社交媒体</a></li>
            <li><a href="#" @click.prevent>订阅资讯</a></li>
          </ul>
        </div>
      </div>
      <div class="footer-bottom">
        <p>&copy; 2024 在线商城. All rights reserved.</p>
    </div>
    </el-footer>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, ShoppingCart, User } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const searchKeyword = ref('')

const categories = [
  { name: '美妆', key: 'makeup', icon: '💄' },
  { name: '服饰', key: 'clothing', icon: '👗' },
  { name: '数码', key: 'digital', icon: '📱' },
  { name: '电器', key: 'appliance', icon: '🔌' },
  { name: '生鲜', key: 'fresh', icon: '🍎' },
  { name: '户外', key: 'outdoor', icon: '🏕️' }
]

// 子分类映射
const subCategoriesMap = {
  'makeup': [
    { name: '面部', key: 'face' },
    { name: '唇部', key: 'lip' },
    { name: '眼部', key: 'eye' }
  ],
  'clothing': [
    { name: '上衣', key: 'top' },
    { name: '下装', key: 'bottom' },
    { name: '配饰', key: 'accessories' }
  ],
  'digital': [
    { name: '手机', key: 'phone' },
    { name: '耳机', key: 'earphone' },
    { name: '配件', key: 'accessories' }
  ],
  'appliance': [
    { name: '厨房电器', key: 'kitchen' },
    { name: '生活电器', key: 'living' }
  ],
  'fresh': [
    { name: '水果', key: 'fruit' },
    { name: '蔬菜', key: 'vegetable' },
    { name: '肉类', key: 'meat' }
  ],
  'outdoor': [
    { name: '装备', key: 'equipment' },
    { name: '服装', key: 'clothing' }
  ]
}

const getSubCategories = (categoryKey) => {
  return subCategoriesMap[categoryKey] || []
}

const activeMenu = computed(() => {
  if (route.path === '/') return 'home'
  if (route.path.startsWith('/category/')) return route.params.category
  return 'home'
})

const currentUser = ref(null)

const cartCount = computed(() => {
  const savedCart = localStorage.getItem('cart')
  if (savedCart) {
    const items = JSON.parse(savedCart)
    return items.reduce((sum, item) => sum + item.quantity, 0)
  }
  return 0
})

const checkUserLogin = () => {
  // 动态导入避免循环依赖
  import('../stores/auth').then(({ useAuthStore }) => {
    const authStore = useAuthStore()
    currentUser.value = authStore.user
  }).catch(() => {
    // fallback到localStorage
  const userStr = localStorage.getItem('user')
  if (userStr) {
    currentUser.value = JSON.parse(userStr)
  }
  })
}

const handleLogout = () => {
  // 动态导入避免循环依赖
  import('../stores/auth').then(({ useAuthStore }) => {
    const authStore = useAuthStore()
    authStore.logout()
    currentUser.value = null
    ElMessage.success('已退出登录')
    router.push('/')
  }).catch(() => {
  localStorage.removeItem('user')
  localStorage.removeItem('token')
  currentUser.value = null
  ElMessage.success('已退出登录')
  router.push('/')
  })
}

onMounted(() => {
  checkUserLogin()
})

watch(() => route.path, () => {
  checkUserLogin()
})

const handleMenuSelect = (key) => {
  if (key === 'home') {
    router.push('/')
  } else if (key.includes('-')) {
    // 子菜单项已处理点击事件，这里不需要额外处理
    return
  } else {
    router.push(`/category/${key}`)
  }
}

const handleSearch = () => {
  if (searchKeyword.value) {
    router.push(`/category/all?search=${searchKeyword.value}`)
  }
}

// 监听路由变化，更新搜索框
watch(() => route.query.search, (newVal) => {
  if (newVal) {
    searchKeyword.value = newVal
  }
})
</script>

<style scoped>
.layout-container {
  min-height: 100vh;
  background: #ffffff;
  max-width: 100%;
  margin: 0;
  box-sizing: border-box;
}

/* 顶部黑条 */
.top-bar {
  background: #000000;
  height: 60px;
  width: 100%;
  display: flex;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 1001;
}

.top-bar-content {
  max-width: 1600px;
  width: 100%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30px;
  box-sizing: border-box;
}

.top-bar-left {
  flex: 1;
  display: flex;
  align-items: center;
}

.top-bar-center {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.top-bar-right {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.brand-name {
  color: #ffffff;
  font-size: 16px;
  font-weight: 300;
  letter-spacing: 2px;
  margin: 0;
  cursor: pointer;
  transition: opacity 0.3s ease;
}

.brand-name:hover {
  opacity: 0.8;
}

.top-search-input {
  width: 250px;
}

.top-search-input :deep(.el-input__inner) {
  background-color: #ffffff;
  border: 1px solid #e8e8e8;
  border-radius: 0;
  color: #000000;
  font-size: 12px;
  padding-left: 24px;
}

.top-search-input :deep(.el-input__inner)::placeholder {
  color: #666666;
}

.top-search-input :deep(.el-input__prefix) {
  color: #666666;
}

.top-link {
  color: #ffffff !important;
  font-size: 12px;
  letter-spacing: 0.5px;
  padding: 0;
  margin: 0;
  cursor: pointer;
  transition: opacity 0.3s ease;
}

.top-link:hover {
  opacity: 0.8;
  background-color: transparent !important;
}

/* 主导航栏 */
.header {
  background: #ffffff;
  box-shadow: none;
  padding: 0;
  border-bottom: 1px solid #e8e8e8;
  position: sticky;
  top: 60px;
  z-index: 1000;
}

.header-content {
  height: 100%;
  max-width: 1600px;
  width: 100%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30px;
  box-sizing: border-box;
}

.logo-area {
  flex: 1;
}

.logo {
  font-size: 20px;
  font-weight: 300;
  letter-spacing: 3px;
  color: #000000;
  cursor: pointer;
  margin: 0;
  white-space: nowrap;
  transition: opacity 0.3s ease;
}

.logo:hover {
  opacity: 0.7;
}

.main-menu {
  flex: 1;
  display: flex;
  justify-content: center;
  border: none;
}

.main-menu :deep(.el-menu-item),
.main-menu :deep(.el-sub-menu__title) {
  font-weight: 400;
  letter-spacing: 0.5px;
  color: #000000;
  border-bottom: none !important;
}

.main-menu :deep(.el-menu-item:hover),
.main-menu :deep(.el-sub-menu__title:hover) {
  background-color: transparent !important;
  color: #000000 !important;
}

.main-menu :deep(.el-menu-item.is-active) {
  border-bottom: 1px solid #000000 !important;
  color: #000000 !important;
}

.header-right {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.cart-button {
  color: #000000 !important;
  padding: 8px;
}

.cart-button:hover {
  background-color: transparent !important;
  opacity: 0.7;
}

.cart-badge {
  position: absolute;
  top: 4px;
  right: 4px;
}

/* 主内容区 */
.main-content {
  background: #ffffff;
  padding: 60px;
  min-height: calc(100vh - 180px);
  max-width: 1600px;
  margin: 0 auto;
  box-sizing: border-box;
}

/* Element Plus 下拉菜单样式覆盖 */
:deep(.el-sub-menu__title) {
  color: #000000 !important;
}

:deep(.el-menu--horizontal .el-sub-menu__title) {
  border-bottom: none !important;
}

/* 页脚样式 */
.footer {
  background: #000000;
  color: #ffffff;
  padding: 60px 60px 30px;
  margin-top: 80px;
  border-top: 1px solid #333333;
}

.footer-content {
  max-width: 1600px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  gap: 60px;
  margin-bottom: 40px;
}

.footer-section {
  flex: 1;
}

.footer-title {
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 2px;
  color: #ffffff;
  margin: 0 0 20px 0;
  text-transform: uppercase;
}

.footer-links {
  list-style: none;
  padding: 0;
  margin: 0;
}

.footer-links li {
  margin-bottom: 12px;
}

.footer-links a {
  color: rgba(255, 255, 255, 0.7);
  font-size: 13px;
  letter-spacing: 0.5px;
  text-decoration: none;
  transition: color 0.3s ease;
}

.footer-links a:hover {
  color: #ffffff;
}

.footer-bottom {
  max-width: 1600px;
  margin: 0 auto;
  padding-top: 30px;
  border-top: 1px solid #333333;
  text-align: center;
}

.footer-bottom p {
  color: rgba(255, 255, 255, 0.5);
  font-size: 12px;
  letter-spacing: 1px;
  margin: 0;
}
</style>
